package com.hnust.service.impl;

import com.hnust.domain.ChapterData;
import com.hnust.service.ChapterService;
import com.hnust.util.IDUtil;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author: Yjx
 * @Data: 2021/10/27 21:40
 * @Version 1.0
 * @Project_Name: teacherSystemBackEnd-master
 * @describe
 */
@Service("chapterService")
public class ChapterServiceImpl implements ChapterService {
    @Override
    public Map<String, Object> readChapter(MultipartFile file, String courseId) throws Exception {
        String filePath = "";
        List<ChapterData> list = new ArrayList<>();
        try{
            filePath = upload(file);
        } catch (Exception e) {
            throw new Exception( "文件上传失败："+e.getMessage());
        }
        Document document = new Document();
        document.loadFromFile(filePath);
        int j=0;
        try {
            //根据专业代码获取专业ID
            Section section = document.getSections().get(0);
            //对于每一段存储数据
            for (j = 0; j < section.getParagraphs().getCount(); j++) {
                Paragraph paragraph = section.getParagraphs().get(j);
                String[] text = paragraph.getText().trim().split(" ");
                String name = text[1];
                text = text[0].split("\\.");
                if(text.length<2) {
                    continue;
                }
                list.add(new ChapterData(name,text[0],text[1],text[2],text[3]));
//                courseDao.insertChapter(IDUtil.getPrimaryKey(),name,Integer.parseInt(text[0]),Integer.parseInt(text[1]),Integer.parseInt(text[2]),Integer.parseInt(text[3]),courseId);
            }
        }catch (Exception e){
            e.printStackTrace();
            if("class org.springframework.dao.DuplicateKeyException".equals(e.getClass().toString())) {
                throw new Exception( "数据已存在-"+"问题可能出现在第"+(j+1)+"组数据");
            } else {
                throw new Exception( "文件读取失败：格式错误-"+"问题可能出现在第"+(j+1)+"组数据");
            }
        }
        //删除文件
        try{
            File willDeleteFile = new File(filePath);
            if(!willDeleteFile.delete()){
                throw new Exception( "文件删除失败！");
            }
        }catch(Exception e){
            throw new Exception("文件删除失败："+e.getMessage());
        }
        Map<String, Object> result = new TreeMap<>();
        result.put("msg","成功");
        result.put("list",list);
        return result;
    }

    /**
     * @Author Tonited
     * @Description //TODO 上传文件，判断文件是否符合规范，最终返回上传文件的路径
     * @Date 16:31 2020/10/29
     * @Param [file]
     * @return java.lang.String
     */
    @Override
    public String upload(MultipartFile file) throws Exception {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if(!".docx".equals(suffixName) && !".doc".equals(suffixName)) {
            throw new Exception("文件不符合规范");
        }
        // 文件上传后的路径
        String filePath = System.getProperty("user.dir") + "/assets/upload/";
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);


        return dest.getAbsolutePath();
    }
}
